<template>
  <el-dialog title="导入" v-model="dialogVisible" width="600px" append-to-body @close="commEvent.onClose">
    <div class="import-container">
      <!-- 厂区选择 -->
      <el-row :gutter="20" class="form-row">
        <template v-if="props.importType === 'plan'">
          <el-col :span="4">
            <span class="label">厂区：</span>
          </el-col>
          <el-col :span="8">
            <el-select v-model="formData.factoryId" placeholder="请选择厂区" style="width: 100%" filterable>
              <el-option v-for="(item, index) in factorys" :key="index" :label="String(item.label)" :value="String(item.value)" />
            </el-select>
          </el-col>
          <el-col :span="12">
            <span class="import-mode">导入模式：更新及新增数据</span>
          </el-col>
        </template>
        <template v-else>
          <el-col :span="24">
            <span class="import-mode">导入模式：更新及新增数据</span>
          </el-col>
        </template>
      </el-row>

      <!-- 注意事项 -->
      <div class="notice-section">
        <template v-if="props.importType === 'plan'">
          <div class="notice-item">
            <span class="notice-dot">·</span>
            <span>订单导入时，须手动选择所属厂区</span>
          </div>
          <div class="notice-item">
            <span class="notice-dot">·</span>
            <span>生产订单号为空的数据自动忽略</span>
          </div>
        </template>
        <template v-else>
          <div class="notice-item">
            <span class="notice-dot">·</span>
            <span>日产数据导入时，系统会自动匹配对应的生产订单</span>
          </div>
          <div class="notice-item">
            <span class="notice-dot">·</span>
            <span>生产订单号为空的数据自动忽略</span>
          </div>
        </template>
        <div class="notice-item">
          <span class="notice-dot">·</span>
          <span>所有数据使用表格中的实际内容，引用其他表格的单元格建议填写实际值，否则无法正确显示内容</span>
        </div>
        <div class="notice-item">
          <span class="notice-dot">·</span>
          <span>固定读取第一个sheet</span>
        </div>
        <!-- <div class="notice-item download-link">
          <span class="notice-dot">·</span>
          <el-link type="primary" @click="commEvent.downloadTemplate">点击下载模板</el-link>
        </div> -->
      </div>

      <!-- 文件上传区域 -->
      <div class="upload-section">
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          :auto-upload="false"
          :show-file-list="true"
          :limit="1"
          accept=".xlsx,.xls"
          :on-change="commEvent.handleFileChange"
          :on-remove="commEvent.handleFileRemove"
        >
          <div class="upload-content">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处或<em>点击选择文件上传</em></div>
          </div>
        </el-upload>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="commEvent.onClose">取消</el-button>
        <el-button type="primary" @click="commEvent.onImport" :loading="importing">导入</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, PropType } from "vue"
import { ElMessage, ElMessageBox, UploadInstance, UploadFile } from "element-plus"
import { UploadFilled } from "@element-plus/icons-vue"
import { EnumProps } from "@/components/ProTable/interface"
import { importOrderPlan, importDailyData } from "@/api/modules/order"

const props = defineProps({
  modelValue: Boolean,
  factorys: { type: Array as PropType<EnumProps[]>, default: () => [] },
  importType: { type: String as PropType<"plan" | "daily">, default: "plan" } // 导入类型：plan-生产计划，daily-日产数据
})

const emit = defineEmits(["update:modelValue", "refresh"])

// 响应式数据
const uploadRef = ref<UploadInstance>()
const importing = ref(false)
const selectedFile = ref<File | null>(null)

const formData = ref({
  factoryId: ""
})
// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val)
})

// 事件处理
const commEvent = {
  // 关闭弹窗
  onClose: () => {
    formData.value.factoryId = ""
    selectedFile.value = null
    uploadRef.value?.clearFiles()
    emit("update:modelValue", false)
  },

  // 下载模板
  downloadTemplate: () => {
    // 这里实现下载模板的逻辑
    ElMessage.info("模板下载功能待实现")
    // 实际项目中可以调用下载API
    // window.open('/api/template/production-plan.xlsx')
  },

  // 文件变化处理
  handleFileChange: (file: UploadFile) => {
    if (file.raw) {
      selectedFile.value = file.raw
      console.log("选择的文件：", file.name)
    }
  },

  // 文件移除处理
  handleFileRemove: () => {
    selectedFile.value = null
    console.log("文件已移除")
  },

  // 导入数据
  onImport: async () => {
    // 验证表单
    if (props.importType === "plan" && !formData.value.factoryId) {
      ElMessage.warning("请选择厂区")
      return
    }

    if (!selectedFile.value) {
      ElMessage.warning("请选择要导入的文件")
      return
    }

    // 确认导入
    try {
      const confirmText = props.importType === "plan" ? "确定要导入生产计划数据吗？" : "确定要导入日产数据吗？"
      await ElMessageBox.confirm(confirmText, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
      importing.value = true

      // 创建FormData
      const formDataToSend = new FormData()
      if (props.importType === "plan") {
        formDataToSend.append("factoryId", formData.value.factoryId)
      }
      formDataToSend.append("file", selectedFile.value)

      // 根据导入类型调用不同的API
      console.log(`开始导入${props.importType === "plan" ? "生产计划" : "日产数据"}，文件：`, selectedFile.value.name)
      let result
      if (props.importType === "plan") {
        result = await importOrderPlan(formDataToSend)
      } else {
        result = await importDailyData(formDataToSend)
      }

      if (result.code !== "200") return
      ElMessage.success("导入成功")
      emit("refresh") // 通知父组件刷新数据
      commEvent.onClose()
    } catch (error) {
      if (error !== "cancel") {
        ElMessage.error("导入失败")
      }
    } finally {
      importing.value = false
    }
  }
}
</script>

<style lang="scss" scoped>
.import-container {
  padding: 20px 0;

  .form-row {
    margin-bottom: 20px;
    align-items: center;

    .label {
      font-size: 14px;
      color: #606266;
    }

    .import-mode {
      font-size: 14px;
      color: #909399;
    }
  }

  .notice-section {
    margin-bottom: 30px;
    background-color: #f5f7fa;
    padding: 15px;
    border-radius: 4px;

    .notice-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 8px;
      font-size: 14px;
      color: #606266;
      line-height: 1.5;

      &:last-child {
        margin-bottom: 0;
      }

      .notice-dot {
        color: #909399;
        margin-right: 8px;
        margin-top: 2px;
      }

      &.download-link {
        .notice-dot {
          color: #409eff;
        }
      }
    }
  }

  .upload-section {
    border: 2px dashed #409eff;
    border-radius: 6px;
    padding: 20px;
    text-align: center;

    .upload-content {
      .el-icon--upload {
        font-size: 48px;
        color: #409eff;
        margin-bottom: 16px;
      }

      .el-upload__text {
        color: #606266;
        font-size: 14px;

        em {
          color: #409eff;
          font-style: normal;
        }
      }
    }
  }
}

.dialog-footer {
  text-align: center;

  .el-button {
    min-width: 80px;
  }
}

:deep(.el-upload-dragger) {
  padding: 20px;
  border: none;
  background: transparent;
}

:deep(.el-upload-list) {
  margin-top: 10px;
}
</style>
